/*
 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * Contributors:
 *     bstefanescu
 */
package org.nuxeo.gwt.habyt.invocation.client.events;

import org.nuxeo.gwt.habyt.invocation.client.Referenceable;

import com.google.gwt.event.logical.shared.HasOpenHandlers;
import com.google.gwt.event.logical.shared.OpenEvent;
import com.google.gwt.event.logical.shared.OpenHandler;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.GwtEvent.Type;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HandlerRegistration;

/**
 * An application context event bus.
 * 
 * Components must explicitly remove their registrations when it is no more
 * needed.
 * 
 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
 * 
 */
public class EventBus implements HasOpenHandlers<Referenceable> {

    private static EventBus instance;

    // public static void installJsBridge() {
    //
    // }

    public static EventBus get() {
        if (instance == null) {
            instance = new EventBus();
        }
        return instance;
    }

    protected HandlerManager bus;

    public EventBus() {
        bus = new HandlerManager(this);
    }

    public <H extends EventHandler> HandlerRegistration addHandler(
            Type<H> type, H handler) {
        return bus.addHandler(type, handler);
    }

    public void fireEvent(GwtEvent<?> event) {
        bus.fireEvent(event);
    }

    @Override
    public HandlerRegistration addOpenHandler(OpenHandler<Referenceable> handler) {
        return addHandler(OpenEvent.getType(), handler);
    }

    public HandlerRegistration addNotificationHandler(
            NotificationEventHandler handler) {
        return addHandler(NotificationEvent.getType(), handler);
    }

    public void fireOpen(Referenceable ref) {
        OpenEvent.fire(this, ref);
    }

}
